<template>
  <div>
    <el-card shadow="always" :body-style="{ padding: '20px' }">
      <template #header>
        <div>
          <span>
            <el-button
              type="primary"
              size="default"
              :icon="Plus"
              @click="addTrademark"
              >添加</el-button
            >
          </span>
        </div>
      </template>
      <!-- card body -->
      <el-table
        :style="{ marginBottom: '30px' }"
        :data="tabelData"
        border
        stripe
      >
        <el-table-column
          label="序号"
          type="index"
          width="80"
          align="center"
        ></el-table-column>
        <el-table-column prop="tmName" label="品牌名称"></el-table-column>
        <el-table-column prop="logoUrl" label="品牌Logo">
          <template #default="{ row }">
            <el-image
            :src="row.logoUrl"
            :lazy="true"
            style="height: 60px"
          ></el-image>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button
              type="warning"
              size="small"
              :icon="Edit"
              @click="updateTrademark(row)"
              >修改</el-button
            >
            <el-button
              type="danger"
              size="small"
              :icon="Delete"
              @click="deleteTrademark(row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
         -->
      <el-pagination
        v-model:page-size="limit"
        v-model:current-page="page"
        :pager-count="5"
        :page-sizes="[3, 7, 5, 9]"
        layout="prev, pager, next,sizes"
        :total="total"
      />
    </el-card>

    <el-dialog
      v-model="dialogFormVisible"
      :title="newTrademark.id ? '修改品牌' : '添加品牌'"
    >
      <el-form
        label-width="100px"
        :model="newTrademark"
        :rules="trademarkRule"
        ref="ruleFormRef"
      >
        <el-form-item label="品牌名称" prop="tmName">
          <el-input autocomplete="off" v-model="newTrademark.tmName" />
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            :action="`${baseUrl}/admin/product/upload`"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="newTrademark.logoUrl"
              :src="newTrademark.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="updateOrAddTrademark"
            >确认</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
  name: "Tradmark",
});
</script>

<script setup lang="ts">
import { ref, toRefs, onMounted, watch, reactive } from "vue";
import { Plus, Edit, Delete } from "@element-plus/icons-vue";
import {
  requestTrademarkList,
  requestUpdateTrademark,
  requestAddTrademark,
  requestDeleteTrademark,
} from "@/api/trademark";
import type {
  reqTrademarkReturnRecordsType,
  reqAddTradeParamsType,
  reqTrademarkReturnItemType,
} from "@/api/trademark";
import { ElMessage, ElMessageBox } from "element-plus";
import type { UploadProps, FormRules ,FormInstance } from "element-plus";
//1.table的逻辑
//table数据
const tabelData = ref<reqTrademarkReturnRecordsType>([]);

//页码逻辑
//页码的数据和类型
interface pageDateType {
  page: number;
  limit: number;
  total: number;
}
const pageDate = ref<pageDateType>({
  page: 1,
  limit: 3,
  total: 100,
});
//解构出页码的属性
const { page, limit, total } = toRefs(pageDate.value);

//监听页码的改变 然后重新发送请求
watch([page, limit], () => {
  getTrademarkList();
});
//3.获取品牌列表
//封装获取品牌列表的功能函数
const getTrademarkList = async () => {
  const result = await requestTrademarkList({
    page: page.value,
    limit: limit.value,
  });
  //把请求回来的值设置给响应数据
  tabelData.value = result.records;
  total.value = result.total;
};
//初始化
onMounted(() => {
  //调用获取品牌列表的功能函数
  getTrademarkList();
});

//4.弹窗逻辑
//控制弹窗显示隐藏的数据
const dialogFormVisible = ref(false);
const baseUrl = import.meta.env.VITE_API_URL;
const newTrademark = ref<reqTrademarkReturnItemType>({
  logoUrl: "",
  tmName: "",
  id: 0,
});
//上传逻辑
const imageUrl = ref("");

const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  newTrademark.value.logoUrl = response.data;
};

const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (rawFile.type !== "image/jpeg") {
    ElMessage.error("Avatar picture must be JPG format!");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("Avatar picture size can not exceed 2MB!");
    return false;
  }
  return true;
};
//5.添加逻辑
const addTrademark = () => {
  // 先清空上一次可能残留的校验信息
  ruleFormRef.value?.clearValidate();
  dialogFormVisible.value = true;
  newTrademark.value = {
    logoUrl: "",
    tmName: "",
    id: 0,
  };
};
//6.修改逻辑
const updateTrademark = async (row: reqTrademarkReturnItemType) => {
   // 先清空上一次可能残留的校验信息
   ruleFormRef.value?.clearValidate();
  dialogFormVisible.value = true;
  //获取当前的数据然后进行回填数据
  //拿到当前的数据浅拷贝赋值给表单的数据newTrademark(为了数据不会互相影响)
  newTrademark.value = { ...row };
};
//7.新增和修改提交
//获取form表单的实例
const ruleFormRef =ref<FormInstance>()
const updateOrAddTrademark = async () => {
  
 try{
 await ruleFormRef.value?.validate()
// console.log(111);

dialogFormVisible.value = false;
  try {
    if (newTrademark.value.id) {
      //修改提交
      await requestUpdateTrademark(newTrademark.value);
      ElMessage.success("修改成功");
    } else {
      // 新增提交
      await requestAddTrademark(newTrademark.value);
      ElMessage.success("新增成功");
      page.value = 1;
    }
    getTrademarkList();
  } catch (e) {
    ElMessage(newTrademark.value.id ? "修改错误" : "新增错误");
   
    
  }
 } catch(e){

 }
  
};

// 8.删除函数
const deleteTrademark = async (id: number) => {
  ElMessageBox.confirm("你确定要删除吗?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      // 删除
      try {
        await requestDeleteTrademark(id);
        //重新发送请求
        getTrademarkList();
        ElMessage.success("删除成功");
      } catch (e) {
        ElMessage.error("删除失败");
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "点错了吧?",
      });
    });
};
//9 表单校验规则
//自定义表单规则函数
const checkTmNameLength = (rule: any, value: string, callback: any) => {
  /* 
    value是当前需要被检验的值
    callback是回调函数,如果有参数则代表错误信息,如果没有参数则代表放行
  */
  if (value.length < 2 || value.length > 10) {
    callback("长度必须是2-5");
  } else {
    callback();
  }
};
const trademarkRule = reactive<FormRules>({
  tmName: [
    { required: true, message: "必须填写品牌名称", trigger: "blur" },
    { validator:checkTmNameLength, message: "长度必须是2-10", trigger: "blur" },
  ],
  logoUrl: [
    {
      required: true,
      message: "必须上传图片",
      trigger: "change",
    },
  ],
});
</script>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
